<template>
  <div class="roles">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加角色 -->
    <el-button type="primary" plain @click="handleAddRole">添加角色</el-button>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      class="mt-15 mb-15"
      :data="tableData"
      border
      style="width: 100%">
      <!-- 表格的展开功能通过 type='expand' 属性并结合插槽来实现 -->
      <el-table-column
        type="expand"
        width="50">
        <template slot-scope="scope">
          <el-row v-for="firstChildItem in scope.row.children" :key="firstChildItem.id">
            <el-col :span="4">
              <!-- 第一层权限 -->
              <el-tag closable @close="handleDeleteTag(scope, scope.row.id, firstChildItem.id)">{{firstChildItem.authName}}</el-tag>
              <!-- 下一级图标 -->
              <i v-if="firstChildItem.children.length>0" class="el-icon-arrow-right"></i>
            </el-col>
            <el-col :span="20">
              <el-row v-for="secondChildItem in firstChildItem.children" :key="secondChildItem.id">
                <el-col :span="4">
                  <!-- 第二层权限 -->
                  <el-tag closable @close="handleDeleteTag(scope, scope.row.id, secondChildItem.id)" type="success">{{secondChildItem.authName}}</el-tag>
                  <!-- 下一级图标 -->
                  <i v-if="secondChildItem.children.length>0" class="el-icon-arrow-right"></i>
                </el-col>
                <el-col :span="20">
                  <!-- 第三层权限 -->
                  <el-tag closable @close="handleDeleteTag(scope, scope.row.id, thirdChildItem.id)" v-for="thirdChildItem in secondChildItem.children" :key="thirdChildItem.id" type="warning">{{thirdChildItem.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <!-- 数据为空提示 -->
          <el-row v-if="scope.row.children.length === 0">
            <el-col :span="24">
              <el-alert
                center
                show-icon
                title="该角色没有分配权限！"
                type="warning"
                description="该角色尚未分配任何权限，请前往分配该角色的权限！"
                :closable="false">
              </el-alert>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名称">
      </el-table-column>
      <el-table-column
        prop="roleDesc"
        label="描述">
      </el-table-column>
      <!-- 操作 -->
      <el-table-column
        label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" plain circle size="mini" @click="handleEditRole(scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" plain circle size="mini" @click="handleDeleteRole(scope.row)" :disabled="scope.row.username==='admin'"></el-button>
          <el-button type="success" icon="el-icon-check" plain circle size="mini" @click="handleRoleRight(scope.row)" :disabled="scope.row.username==='admin'"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加角色弹框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogFormVisible">
      <!-- addForm表单数据，:rules属性传入校验规则，prop指定需要校验的字段名 -->
      <el-form :model="addRoleForm" :rules="addrolerules" ref="addRoleRef">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="addRoleForm.roleName" autocomplete="off" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc" autocomplete="off" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmAddRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑角色弹框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialogFormVisible">
      <!-- addForm表单数据，:rules属性传入校验规则，prop指定需要校验的字段名 -->
      <el-form :model="editRoleForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="editRoleForm.roleName" autocomplete="off" placeholder="请输入角色名称" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc" autocomplete="off" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmEditRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑角色权限弹框 -->
    <el-dialog title="编辑角色权限" :visible.sync="editRoleRightDialogFormVisible">
      <div class="tree-container">
        <el-tree
          ref="rightTreeRef"
          :data="roleRights"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="selectedIds"
          :props="defaultProps">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRoleRightDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmEditRoleRight">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, deleteRoleRight, addRole, deleteRole, editRole, getRights, comfirmRoleRight } from '@/api'
export default {
  data () {
    return {
      loading: false,
      tableData: [],
      formLabelWidth: '20%',
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleDialogFormVisible: false,
      addrolerules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      editRoleDialogFormVisible: false,
      editRoleForm: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      editRoleRightDialogFormVisible: false,
      roleRights: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      selectedIds: [],
      roleId: ''
    }
  },
  mounted () {
    this.initTable()
  },
  methods: {
    // 初始化表格
    initTable () {
      this.loading = true
      getRoles().then(res => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          this.tableData = res.data.data
          this.loading = false
          // this.$message.success(res.data.meta.msg)
        } else {
          this.$message.error(res.data.meta.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 删除角色权限
    handleDeleteTag (scope, roleId, rightId) {
      console.log(scope)
      deleteRoleRight(roleId, rightId).then(res => {
        // console.log(res)
        scope.row.children = res.data.data
        if (res.data.meta.status === 200) {
          this.$message.success(res.data.meta.msg)
        } else {
          this.$message.error(res.data.meta.msg)
        }
      })
    },
    // 添加角色
    handleAddRole () {
      this.addRoleDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.addRoleRef.clearValidate()
      })
    },
    // 确认添加角色
    confirmAddRole () {
      this.$refs.addRoleRef.validate(isPass => {
        if (isPass) {
          addRole(this.addRoleForm).then(res => {
            if (res.data.meta.status === 201) {
              this.$message.success(res.data.meta.msg)
              this.addRoleForm.roleName = ''
              this.addRoleForm.roleDesc = ''
              this.addRoleDialogFormVisible = false
              this.initTable()
            } else {
              this.$message.error(res.data.meta.msg)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 删除角色
    handleDeleteRole (row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log(row)
        deleteRole(row.id).then(res => {
          // console.log(res)
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.initTable()
          } else {
            this.$message.error(res.data.meta.msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 编辑角色
    handleEditRole (row) {
      // console.log(row)
      this.editRoleDialogFormVisible = true
      this.editRoleForm.roleName = row.roleName
      this.editRoleForm.roleDesc = row.roleDesc
      this.editRoleForm.id = row.id
    },
    // 确认编辑角色
    confirmEditRole () {
      editRole(this.editRoleForm).then(res => {
        // console.log(res)
        if (res.data.meta.status === 200) {
          this.editRoleDialogFormVisible = false
          this.$message.success('修改成功')
          this.initTable()
        } else {
          this.$message.error(res.data.meta.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 设置角色权限
    handleRoleRight (row) {
      // 保存该角色id, 以便提交用户角色权限使用
      this.roleId = row.id
      // 显示
      this.editRoleRightDialogFormVisible = true
      getRights('tree').then(res => {
        // console.log(res)
        this.roleRights = res.data.data
      }).catch(err => {
        console.log(err)
      })
      // 循环之前先将数据清空，否则将会拿到上一次点击选中的数据
      this.selectedIds = []
      // 从row中获取当前角色具有的权限, 只需将第三层的id拿出来赋值给数组
      row.children.forEach(firstItem => {
        if (firstItem.children && firstItem.children.length > 0) {
          firstItem.children.forEach(secondItem => {
            if (secondItem.children && secondItem.children.length > 0) {
              secondItem.children.forEach(thirdItem => {
                // 将第三层的数据权限id放进数组中
                this.selectedIds.push(thirdItem.id)
              })
            }
          })
        }
      })
    },
    // 确认角色权限
    confirmEditRoleRight () {
      // 获取到全选的权限
      let allCheckedKeys = this.$refs.rightTreeRef.getCheckedKeys()
      // 获取到半选的权限
      let halfCheckedKeys = this.$refs.rightTreeRef.getHalfCheckedKeys()
      // 所有全选和半选的权限id
      // 合并数组 concat()方法 或者 ...展开运算符
      let allKeys = [...allCheckedKeys, ...halfCheckedKeys]
      // 接口要求是逗号隔开的字符串
      let idsStr = allKeys.join(',')
      // 提交
      comfirmRoleRight(this.roleId, idsStr).then(res => {
        console.log(res)
        if (res.data.meta.status === 200) {
          this.editRoleRightDialogFormVisible = false
          this.$message.success(res.data.meta.msg)
          this.initTable()
        } else {
          this.$message.error(res.data.meta.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-row {
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .el-tag {
    margin: 2px 5px;
  }
  .roles {
    .tree-container {
      height: 300px;
      overflow: auto;
    }
  }
</style>
